/*
 * Copyright (c) 2016-2017 fulihui.com All right reserved
 * Project: integral-business-parent
 * File name: ZbusIntegralBusinessHandler.java
 */

package com.fulihui.integralbusiness.consumer;

import com.alibaba.fastjson.JSONObject;
import com.fulihui.integralbusiness.constants.IntegralBusinessFlags;
import com.fulihui.integralbusiness.handler.IntegralBusinessHandler;
import com.fulihui.integralbusiness.handler.IntegralBusinessSelector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zbus.broker.Broker;
import org.zbus.broker.ZbusBroker;
import org.zbus.mq.Consumer;

import javax.annotation.PostConstruct;

import static com.fulihui.integralbusiness.constants.IntegralBusinessConstants.ZBUS_MQ_NAME_PREFIX;

/**
 * @author Willard.Hu on 2017/4/21 0021.
 */
public class ZbusIntegralBusinessConsumer {
    private transient final Logger log = LoggerFactory.getLogger(getClass());

    private String                   address;
    private IntegralBusinessSelector selector;

    @PostConstruct
    void init() throws Exception {
        Broker broker = new ZbusBroker(address);
        for (IntegralBusinessFlags flag : IntegralBusinessFlags.values()) {
            new Consumer(broker, ZBUS_MQ_NAME_PREFIX + flag.name()).start((msg, consumer) -> {
                try {
                    IntegralBusinessHandler handler = selector.getHandler(flag);
                    if (handler == null) {
                        throw new IllegalArgumentException("Not found handler:" + flag.name());
                    }
                    handler.handle(JSONObject.parseObject(msg.getBodyString()));
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            });
        }
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public void setSelector(IntegralBusinessSelector selector) {
        this.selector = selector;
    }
}
